<?php
/**
 * @package WKernel
 */
require_once 'WKernel/Data/Serializer/Int.php';
require_once 'WKernel/Markup/Document.php';
class WK_Data_Serializer_Xml implements WK_Data_Serializer_Int {
	private $data;
	private $xmldoc;
	
	private $str;
	
	public function __construct(WK_Data_Map $data){
		$this->data = $data;
		$this->xmldoc = new WK_Markup_Document();
		$this->xmldoc->setNamespace('http://www.wolfram.bratin.ru/XSD/Data/', '');
		$this->xmldoc->setSchema('http://wolfram.libs/XSD/Data.xsd?9');
	}
	
	/**
	 * (non-PHPdoc)
	 * @see WKernel/Data/Serializer/WK_Data_Serializer_Int::serialize()
	 */
	public function serialize($omit_declaration = true){
		$this->str = $this->serializeNode('data', $this->data->__toArray(), 0, $omit_declaration);		
		return trim($this->str);
	}
	
	public function serializeNode($name, &$node, $level, $omit_declaration){
		if(!is_array($node)){
			return $this->xmldoc->createElement($name, array(), $node, $level, 2, true);
		}
		
		$keys   = array_keys($node);
		$result = '';
		if(is_integer(key($node))) {
			foreach($keys as $i => $key)
				$result .= $this->serializeNode($name, $node[$key], $level, $omit_declaration);
		}
		else{
			$result .= $this->xmldoc->openElement($name, array(), $level);
			foreach($keys as $i => $key)
				$result .= $this->serializeNode($key, $node[$key], $level + 1, $omit_declaration);
			$result .= $this->xmldoc->closeElement($name, $level);
		}
		return $result;
	}	
}